#pragma once

#include<iostream>
#include<string>
#include<cstdio>
#include<set>
#define line_size 1024
class Command{
    public:
        Command()
        {
            allow_commands.insert("ls");
            allow_commands.insert("pwd");
            allow_commands.insert("ls -l");
            allow_commands.insert("ll");
            allow_commands.insert("touch");
            allow_commands.insert("who");
            allow_commands.insert("whoami");
        }
        bool CheckCommand(std::string command)
        {
            if(allow_commands.find(command)!= allow_commands.end()){
                return true;
            }
            return false;
        }
        std::string Excute(std::string command)
        {
            // 1. pipe
            // 2. fork + dup2(pipe[1], 1) + exec* , 执行结果给父进程，pipe[0]
            // 3. return
            // FILE *popen(const char *command, const char *type);
            // int pclose(FILE * stream);
            if(!CheckCommand(command)){
                return std::string("No such command!");
            }
            FILE *fp = popen(command.c_str(), "r");
            if(nullptr == fp){
                return std::string("popen error!");
            }
            char buffer[line_size];
            std::string result;
            while(fgets(buffer, sizeof(buffer), fp)!= nullptr){
                result += buffer;
            }
            pclose(fp);
            return result;
        }

    private:
        std::set<std::string> allow_commands;
};